<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>步态分析系统 - 管理员控制台</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!-- Element Plus Icons -->
    <link rel="stylesheet" href="https://unpkg.com/@element-plus/icons-vue/dist/index.css">
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    <!-- Element Plus -->
    <script src="https://unpkg.com/element-plus"></script>
    <!-- Element Plus Icons -->
    <script src="https://unpkg.com/@element-plus/icons-vue"></script>
    <!-- ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        /* 全局样式 */
        :root {
            --primary-color: #409EFF;
            --success-color: #67C23A;
            --warning-color: #E6A23C;
            --danger-color: #F56C6C;
            --text-color: #303133;
            --border-color: #DCDFE6;
            --gradient-start: #409EFF;
            --gradient-end: #67C23A;
        }

        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
            color: var(--text-color);
            min-height: 100vh;
        }

        .admin-container {
            padding: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: linear-gradient(to right, var(--gradient-start), var(--gradient-end));
            border-bottom: 1px solid var(--border-color);
            padding: 0 20px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header h2 {
            margin: 0;
            color: white;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .el-dropdown-link {
            cursor: pointer;
            color: white;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .el-tabs {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }

        .task-card {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .task-card:hover {
            transform: translateY(-5px);
        }

        .task-card h3 {
            margin-top: 0;
            color: var(--primary-color);
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 10px;
        }

        .task-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .stat-item {
            background: linear-gradient(135deg, #fff 0%, #f5f7fa 100%);
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s ease;
        }

        .stat-item:hover {
            transform: translateY(-3px);
        }

        .stat-item .value {
            font-size: 28px;
            font-weight: bold;
            color: var(--primary-color);
            margin-bottom: 5px;
        }

        .stat-item .label {
            color: #909399;
            font-size: 14px;
        }

        .chart-container {
            height: 400px;
            margin: 20px 0;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
            position: relative;
        }

        .chart-container:hover {
            transform: translateY(-5px);
        }

        .chart-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .chart-title {
            position: absolute;
            top: 10px;
            left: 20px;
            margin: 0;
            font-size: 16px;
            font-weight: 500;
            color: var(--text-color);
            z-index: 1;
        }

        .chart-content {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            padding: 20px;
        }

        .task-form {
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }

        .task-form:hover {
            transform: translateY(-5px);
        }

        .task-form h3 {
            color: var(--primary-color);
            margin-top: 0;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-color);
        }

        .task-form .el-form-item {
            margin-bottom: 20px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .el-button {
            border-radius: 4px;
            transition: all 0.3s ease;
        }

        .el-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .el-button--primary {
            background: linear-gradient(to right, var(--gradient-start), var(--gradient-end));
            border: none;
        }

        .el-button--success {
            background: linear-gradient(to right, #67C23A, #85ce61);
            border: none;
        }

        .el-button--warning {
            background: linear-gradient(to right, #E6A23C, #f0c78a);
            border: none;
        }

        .el-button--danger {
            background: linear-gradient(to right, #F56C6C, #f78989);
            border: none;
        }

        .task-result {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid var(--primary-color);
        }

        .task-result h4 {
            margin-top: 0;
            color: var(--primary-color);
        }

        .task-result pre {
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            overflow-x: auto;
        }

        .loading-overlay {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.9);
            padding: 10px 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 1000;
            pointer-events: none; /* 允许点击穿透 */
            transition: opacity 0.3s ease;
            opacity: 0;  /* 默认不可见 */
        }

        /* 当loading为true时显示 */
        .loading-overlay.visible {
            opacity: 1;
        }

        .loading-spinner {
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .monitor-container,
        .control-container,
        .alert-container {
            margin: 20px 0;
        }

        .status-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .status-card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .status-card:hover {
            transform: translateY(-5px);
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            padding: 15px;
        }

        .status-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            background: #f5f7fa;
            border-radius: 6px;
            transition: background-color 0.3s ease;
        }

        .status-item:hover {
            background: #e6e8eb;
        }

        .status-item i {
            font-size: 20px;
            color: var(--primary-color);
        }

        .motor-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            padding: 15px;
        }

        .motor-item {
            padding: 10px;
            background: #f5f7fa;
            border-radius: 6px;
            text-align: center;
            transition: background-color 0.3s ease;
        }

        .motor-item:hover {
            background: #e6e8eb;
        }

        .imu-data {
            padding: 15px;
        }

        .imu-section {
            margin-bottom: 20px;
        }

        .imu-section h4 {
            margin: 0 0 10px 0;
            color: var(--primary-color);
        }

        .imu-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
        }

        .imu-item {
            padding: 10px;
            background: #f5f7fa;
            border-radius: 6px;
            text-align: center;
            transition: background-color 0.3s ease;
        }

        .imu-item:hover {
            background: #e6e8eb;
        }

        .gps-data {
            padding: 15px;
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }

        .gps-item {
            padding: 10px;
            background: #f5f7fa;
            border-radius: 6px;
            text-align: center;
            transition: background-color 0.3s ease;
        }

        .gps-item:hover {
            background: #e6e8eb;
        }

        .control-card,
        .task-card,
        .alert-card {
            margin-bottom: 20px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .task-list {
            margin-top: 20px;
        }

        .battery-status {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .battery-level {
            margin-bottom: 20px;
        }

        .battery-level h4 {
            margin-bottom: 10px;
        }

        .battery-voltage {
            margin-bottom: 20px;
        }

        .battery-voltage h4 {
            margin-bottom: 10px;
        }

        .battery-chart {
            width: 100%;
        }

        .monitor-charts {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .motor-charts {
            margin-top: 20px;
        }

        .monitor-container {
            padding: 20px;
        }

        .chart-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-top: 20px;
        }

        .chart {
            height: 400px;
            width: 100%;
            padding: 20px;
        }

        .monitor-container {
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .status-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .charts-container {
            padding: 20px;
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .chart-card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .chart-card.full-width {
            grid-column: 1 / -1;
        }

        .chart {
            height: 400px;
            width: 100%;
            padding: 20px;
        }

        .motor-tabs .chart {
            height: 600px;
            padding: 20px 40px 40px 40px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            border-bottom: 1px solid #ebeef5;
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            padding: 15px;
        }

        .status-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px;
            background: #f5f7fa;
            border-radius: 6px;
            font-size: 14px;
        }

        .battery-status {
            padding: 20px;
        }

        .battery-level,
        .battery-voltage {
            margin-bottom: 20px;
        }

        .battery-level h4,
        .battery-voltage h4 {
            margin: 0 0 10px 0;
            color: #606266;
            font-size: 14px;
        }

        .el-progress {
            margin-bottom: 15px;
        }

        .motor-tabs {
            padding: 20px;
        }

        .motor-tabs .el-tabs__content {
            padding-top: 20px;
        }

        /* 响应式布局 */
        @media screen and (max-width: 1200px) {
            .chart-grid {
                grid-template-columns: 1fr;
            }
        }

        @media screen and (max-width: 768px) {
            .status-cards {
                grid-template-columns: 1fr;
            }
            .chart-container {
                height: 300px;
            }
        }

        .safety-locks {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .data-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .status-content {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .status-value {
            font-size: 24px;
            font-weight: bold;
            color: #409EFF;
        }

        .status-label {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
        }

        .analytics-section {
            margin-top: 20px;
            padding: 20px;
        }

        .chart-card {
            margin-bottom: 20px;
            box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
        }

        .chart-card .el-card__body {
            padding: 20px;
        }

        .alert-stats .el-card {
            margin-bottom: 20px;
        }

        .alert-stats .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .alert-stats .card-content {
            text-align: center;
            padding: 20px 0;
        }

        .alert-stats .number {
            font-size: 24px;
            font-weight: bold;
            color: #409EFF;
        }

        .alert-stats .warning {
            color: #E6A23C;
        }

        .overview-container {
            padding: 20px;
        }

        .status-cards {
            margin-bottom: 30px;
        }

        .status-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            padding: 10px;
        }

        .status-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px;
            background: #f5f7fa;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .status-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .chart-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 30px;
            margin-top: 30px;
        }

        .chart-container {
            background: white;
            border-radius: 8px;
            padding: 25px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            height: 400px;
        }

        .chart-title {
            margin: 0 0 20px 0;
            color: #303133;
            font-size: 16px;
            font-weight: 500;
            padding-bottom: 15px;
            border-bottom: 1px solid #ebeef5;
        }

        .chart-content {
            height: calc(100% - 50px);
            width: 100%;
        }

        @media screen and (max-width: 1200px) {
            .chart-grid {
                grid-template-columns: 1fr;
            }
            
            .status-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media screen and (max-width: 768px) {
            .status-grid {
                grid-template-columns: 1fr;
            }
            
            .chart-container {
                height: 350px;
            }
        }
        
        /* 个人中心相关样式 */
        .profile-container {
            padding: 20px;
        }
        
        .profile-card {
            text-align: center;
            padding: 30px 20px;
        }
        
        .profile-avatar {
            margin-bottom: 20px;
        }
        
        .profile-info h2 {
            margin-top: 10px;
            margin-bottom: 15px;
        }
        
        .profile-info p {
            margin: 10px 0;
        }
        
        .profile-menu {
            border-right: none;
        }
        
        .profile-menu .el-menu-item {
            padding: 0 20px;
            height: 50px;
            line-height: 50px;
        }
        
        .profile-menu .el-menu-item i {
            margin-right: 10px;
        }
        
        .mfa-section {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .pagination-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div id="app" v-cloak>
        <!-- Header -->
        <header class="header">
            <h2>步态分析系统 - 管理员控制台</h2>
            <div class="header-right">
                <span>欢迎，{{username}}</span>
                <el-button type="danger" size="small" @click="handleLogout">退出</el-button>
            </div>
        </header>

        <!-- Main Content -->
        <div class="admin-container">
            <el-tabs v-model="activeTab">
                <!-- Overview Tab -->
                <el-tab-pane label="系统概览" name="overview">
                    <div class="overview-container">
                        <!-- Status Cards -->
                        <div class="status-cards">
                            <el-card class="status-card">
                                <div class="status-grid">
                                    <div class="status-item">
                                        <i class="el-icon-user"></i>
                                        <div>
                                            <div>总用户数</div>
                                            <div>{{ stats.total_users || 0 }}</div>
                                        </div>
                                    </div>
                                    <div class="status-item">
                                        <i class="el-icon-user"></i>
                                        <div>
                                            <div>活跃用户</div>
                                            <div>{{ stats.active_users || 0 }}</div>
                                        </div>
                                    </div>
                                    <div class="status-item">
                                        <i class="el-icon-warning"></i>
                                        <div>
                                            <div>告警数量</div>
                                            <div>{{ stats.alerts || 0 }}</div>
                                        </div>
                                    </div>
                                </div>
                            </el-card>
                        </div>

                        <!-- Charts Grid -->
                        <div class="chart-grid">
                            <!-- User Activity Trend -->
                            <el-card class="chart-card">
                                <div class="chart-container" id="userTrendChart"></div>
                            </el-card>

                            <!-- Alert Trend -->
                            <el-card class="chart-card">
                                <div class="chart-container" id="alertTrendChart"></div>
                            </el-card>
                        </div>
                    </div>
                </el-tab-pane>

                <!-- Control Panel Tab -->
                <el-tab-pane label="控制面板" name="control">
                <div class="control-container">
                    <el-card class="control-card">
                        <template #header>
                            <div class="card-header">
                                    <span>运动控制</span>
                                    <el-button type="danger" @click="emergencyStop">紧急停止</el-button>
                            </div>
                        </template>
                            <el-form :model="controlForm" label-width="120px">
                            <el-form-item label="步态类型">
                                    <el-select v-model="controlForm.gait_type">
                                        <el-option label="步行" value="walk"></el-option>
                                    <el-option label="跑步" value="run"></el-option>
                                        <el-option label="跳跃" value="jump"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="速度">
                                <el-slider v-model="controlForm.speed" :min="0" :max="100"></el-slider>
                            </el-form-item>
                            <el-form-item label="方向">
                                    <el-select v-model="controlForm.direction">
                                        <el-option label="前进" value="forward"></el-option>
                                        <el-option label="后退" value="backward"></el-option>
                                        <el-option label="左转" value="left"></el-option>
                                        <el-option label="右转" value="right"></el-option>
                                    </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="sendControl">发送控制指令</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                </div>
            </el-tab-pane>

                <!-- User Management Tab -->
                <el-tab-pane label="用户管理" name="users">
                    <el-table :data="users" style="width: 100%">
                        <el-table-column prop="id" label="ID" width="80"></el-table-column>
                        <el-table-column prop="username" label="用户名"></el-table-column>
                        <el-table-column prop="email" label="邮箱"></el-table-column>
                        <el-table-column prop="created_at" label="创建时间">
                                <template #default="scope">
                                {{ formatDate(scope.row.created_at) }}
                                </template>
                            </el-table-column>
                        <el-table-column label="操作" width="150">
                                <template #default="scope">
                                <el-button size="small" type="danger" @click="handleUserAction('delete', scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
            </el-tab-pane>

                <!-- Alert Management Tab -->
            <el-tab-pane label="告警管理" name="alerts">
                        <el-table :data="alerts" style="width: 100%">
                        <el-table-column prop="id" label="ID" width="80"></el-table-column>
                            <el-table-column prop="level" label="级别">
                                <template #default="scope">
                                    <el-tag :type="getAlertLevelType(scope.row.level)">
                                        {{ scope.row.level }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="message" label="消息"></el-table-column>
                        <el-table-column prop="created_at" label="时间">
                                <template #default="scope">
                                {{ formatDate(scope.row.created_at) }}
                                </template>
                            </el-table-column>
                        <el-table-column label="操作" width="150">
                                <template #default="scope">
                                <el-button size="small" type="primary" @click="handleAlertAction('resolve', scope.row)">处理</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
            </el-tab-pane>

                <!-- Safety Settings Tab -->
                <el-tab-pane label="安全设置" name="settings">
                <div class="safety-locks">
                        <h3>安全锁设置</h3>
                    <el-form :model="safetyLocks" label-width="150px">
                        <el-form-item label="最大电机温度(°C)">
                            <el-input-number v-model="safetyLocks.max_motor_temp" :min="0" :max="100"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大CPU使用率(%)">
                            <el-input-number v-model="safetyLocks.max_cpu_usage" :min="0" :max="100"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大内存使用率(%)">
                            <el-input-number v-model="safetyLocks.max_memory_usage" :min="0" :max="100"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大晃动角度(°)">
                            <el-input-number v-model="safetyLocks.max_sway_angle" :min="0" :max="90"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最小电池电量(%)">
                            <el-input-number v-model="safetyLocks.min_battery_level" :min="0" :max="100"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大步幅(mm)">
                            <el-input-number v-model="safetyLocks.max_stride_length" :min="0" :max="500"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大步高(mm)">
                            <el-input-number v-model="safetyLocks.max_step_height" :min="0" :max="300"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最小时间间隔(s)">
                            <el-input-number v-model="safetyLocks.min_time_interval" :min="0" :max="10"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大点数">
                            <el-input-number v-model="safetyLocks.max_point_count" :min="0" :max="2000"></el-input-number>
                        </el-form-item>
                        <el-form-item>
                                <el-button type="primary" @click="updateSafetyLocks">保存设置</el-button>
                            <el-button @click="resetSafetyLocks">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>

                <!-- Data Analysis Tab -->
                <el-tab-pane label="数据分析" name="analysis">
                    <div class="analytics-section">
                        <!-- Add refresh button -->
                        <div style="margin-bottom: 20px; text-align: right;">
                            <el-button type="primary" :loading="loading" @click="handleAnalyticsRefresh">
                                <i class="el-icon-refresh"></i> 刷新数据
                            </el-button>
                        </div>

                        <!-- Analysis Conclusions -->
                        <el-card class="conclusion-card" style="margin-bottom: 30px;">
                            <template #header>
                                <div class="card-header">
                                    <span><strong>数据分析结论与建议</strong></span>
                                </div>
                            </template>
                            <div class="conclusion-content">
                                <el-collapse v-model="activeConclusions">
                                    <el-collapse-item title="耗电量分析结论" name="power">
                                        <div class="conclusion-item">
                                            <h4>关键发现：</h4>
                                            <ul>
                                                <li v-if="powerConsumptionConclusion.highType">步态类型 <strong>{{ powerConsumptionConclusion.highType }}</strong> 耗电量最高，平均值为 {{ powerConsumptionConclusion.highValue }}W。</li>
                                                <li v-if="powerConsumptionConclusion.lowType">步态类型 <strong>{{ powerConsumptionConclusion.lowType }}</strong> 耗电量最低，平均值为 {{ powerConsumptionConclusion.lowValue }}W。</li>
                                                <li>峰值耗电时段: {{ powerConsumptionConclusion.peakTime || '暂无数据' }}</li>
                                                <li>电量使用趋势: {{ powerConsumptionConclusion.trend || '暂无数据' }}</li>
                                            </ul>
                                            <h4>建议：</h4>
                                            <p>{{ powerConsumptionConclusion.recommendation || '暂无建议' }}</p>
                                            <div v-if="powerConsumptionConclusion.alert" class="alert-message" style="color: #F56C6C; margin-top: 10px;">
                                                <i class="el-icon-warning"></i> 
                                                <span>{{ powerConsumptionConclusion.alert }}</span>
                                            </div>
                                        </div>
                                    </el-collapse-item>
                                    
                                    <el-collapse-item title="机身晃动分析结论" name="sway">
                                        <div class="conclusion-item">
                                            <h4>关键发现：</h4>
                                            <ul>
                                                <li v-if="bodySwayConclusion.highType">步态类型 <strong>{{ bodySwayConclusion.highType }}</strong> 晃动最大，平均值为 {{ bodySwayConclusion.highValue }}°。</li>
                                                <li v-if="bodySwayConclusion.lowType">步态类型 <strong>{{ bodySwayConclusion.lowType }}</strong> 晃动最小，平均值为 {{ bodySwayConclusion.lowValue }}°。</li>
                                                <li>稳定性趋势: {{ bodySwayConclusion.trend || '暂无数据' }}</li>
                                            </ul>
                                            <h4>建议：</h4>
                                            <p>{{ bodySwayConclusion.recommendation || '暂无建议' }}</p>
                                            <div v-if="bodySwayConclusion.alert" class="alert-message" style="color: #F56C6C; margin-top: 10px;">
                                                <i class="el-icon-warning"></i> 
                                                <span>{{ bodySwayConclusion.alert }}</span>
                                            </div>
                                        </div>
                                    </el-collapse-item>
                                    
                                    <el-collapse-item title="CPU负载分析结论" name="cpu">
                                        <div class="conclusion-item">
                                            <h4>关键发现：</h4>
                                            <ul>
                                                <li>最高CPU负载: {{ cpuLoadConclusion.maxLoad || '暂无数据' }}%（点位数: {{ cpuLoadConclusion.maxLoadPoints || '未知' }}，轨迹长度: {{ cpuLoadConclusion.maxLoadLength || '未知' }}mm）</li>
                                                <li>最佳性能组合: 点位数 {{ cpuLoadConclusion.optimalPoints || '未知' }}，轨迹长度 {{ cpuLoadConclusion.optimalLength || '未知' }}mm</li>
                                                <li>负载瓶颈因素: {{ cpuLoadConclusion.bottleneck || '暂无数据' }}</li>
                                            </ul>
                                            <h4>建议：</h4>
                                            <p>{{ cpuLoadConclusion.recommendation || '暂无建议' }}</p>
                                            <div v-if="cpuLoadConclusion.alert" class="alert-message" style="color: #F56C6C; margin-top: 10px;">
                                                <i class="el-icon-warning"></i> 
                                                <span>{{ cpuLoadConclusion.alert }}</span>
                                            </div>
                                        </div>
                                    </el-collapse-item>
                                    
                                    <el-collapse-item title="内存使用分析结论" name="memory">
                                        <div class="conclusion-item">
                                            <h4>关键发现：</h4>
                                            <ul>
                                                <li>最高内存使用: {{ memoryUsageConclusion.maxUsage || '暂无数据' }}%（点位数: {{ memoryUsageConclusion.maxUsagePoints || '未知' }}，轨迹长度: {{ memoryUsageConclusion.maxUsageLength || '未知' }}mm）</li>
                                                <li>内存使用趋势: {{ memoryUsageConclusion.trend || '暂无数据' }}</li>
                                                <li>点位数对内存影响: {{ memoryUsageConclusion.pointsImpact || '暂无数据' }}</li>
                                            </ul>
                                            <h4>建议：</h4>
                                            <p>{{ memoryUsageConclusion.recommendation || '暂无建议' }}</p>
                                            <div v-if="memoryUsageConclusion.alert" class="alert-message" style="color: #F56C6C; margin-top: 10px;">
                                                <i class="el-icon-warning"></i> 
                                                <span>{{ memoryUsageConclusion.alert }}</span>
                                            </div>
                                        </div>
                                    </el-collapse-item>
                                    
                                    <el-collapse-item title="电机温度分析结论" name="motor">
                                        <div class="conclusion-item">
                                            <h4>关键发现：</h4>
                                            <ul>
                                                <li>温度最高参数: {{ motorTempConclusion.highestParam || '暂无数据' }} ({{ motorTempConclusion.highestValue || '0' }}°C)</li>
                                                <li>安全运行范围: {{ motorTempConclusion.safeRange || '暂无数据' }}</li>
                                                <li>温度上升速率: {{ motorTempConclusion.riseRate || '暂无数据' }}</li>
                                            </ul>
                                            <h4>建议：</h4>
                                            <p>{{ motorTempConclusion.recommendation || '暂无建议' }}</p>
                                            <div v-if="motorTempConclusion.alert" class="alert-message" style="color: #F56C6C; margin-top: 10px;">
                                                <i class="el-icon-warning"></i> 
                                                <span>{{ motorTempConclusion.alert }}</span>
                                            </div>
                                        </div>
                                    </el-collapse-item>
                                </el-collapse>
                            </div>
                        </el-card>

                        <!-- Analysis Charts -->
                        <div class="chart-grid">
                            <!-- Power Consumption Chart -->
                            <el-card class="chart-card">
                                <div class="chart-container" id="powerConsumptionChart"></div>
                            </el-card>

                            <!-- Body Sway Chart -->
                            <el-card class="chart-card">
                                <div class="chart-container" id="bodySwayChart"></div>
                            </el-card>

                            <!-- CPU Load Chart -->
                            <el-card class="chart-card">
                                <div class="chart-container" id="cpuLoadChart"></div>
                            </el-card>

                            <!-- Memory Usage Chart -->
                            <el-card class="chart-card">
                                <div class="chart-container" id="memoryUsageChart"></div>
                            </el-card>

                            <!-- Motor Temperature Chart -->
                            <el-card class="chart-card">
                                <div class="chart-container" id="motorTempChart"></div>
                            </el-card>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- Loading Overlay -->
        <div class="loading-overlay" :class="{ visible: loading }" v-show="loading">
            <div class="loading-spinner"></div>
            <span>加载中...</span>
        </div>
    </div>

    <script>
        // 配置axios默认值
        axios.defaults.baseURL = 'http://8.137.14.132:5000';  // 设置API服务器地址
        axios.defaults.timeout = 10000;  // 设置超时时间为10秒
        axios.defaults.headers.common['Content-Type'] = 'application/json';

        // 添加请求拦截器
        axios.interceptors.request.use(
            config => {
                // 从localStorage获取token
                        const token = localStorage.getItem('token');
                        if (token) {
                            config.headers.Authorization = `Bearer ${token}`;
                        }
                        return config;
            },
            error => {
                console.error('请求拦截器错误:', error);
                        return Promise.reject(error);
            }
        );

        // 添加响应拦截器
                    axios.interceptors.response.use(
                        response => response,
                        error => {
                if (error.code === 'ECONNABORTED') {
                    console.error('请求超时');
                                ElMessage.error('请求超时，请检查网络连接');
                } else if (!error.response) {
                    console.error('网络错误');
                    ElMessage.error('无法连接到服务器，请检查网络连接');
                            } else {
                    console.error('响应错误:', error.response.data);
                    ElMessage.error(error.response.data.message || '服务器响应错误');
                            }
                            return Promise.reject(error);
                        }
                    );

        const { createApp, ref, onMounted, onUnmounted, nextTick, watch, computed } = Vue
        const { ElMessage, ElMessageBox } = ElementPlus

        const app = createApp({
            setup() {
                const loading = ref(false);
                const activeTab = ref('overview');
                const stats = ref({
                    total_users: 0,
                    active_users: 0,
                    alerts: 0
                });
                const users = ref([]);
                const alerts = ref([]);
                const charts = ref({
                    userActivity: null,
                    alertTrend: null,
                    powerConsumption: null,
                    bodySway: null,
                    cpuLoad: null,
                    memoryUsage: null,
                    motorTemp: null
                });
                const controlForm = ref({
                    gait_type: '',
                    speed: 0,
                    direction: ''
                });
                const safetyLocks = ref({
                    max_motor_temp: 45.0,
                    max_cpu_usage: 80.0,
                    max_memory_usage: 90.0,
                    max_sway_angle: 30.0,
                    min_battery_level: 20.0,
                    max_stride_length: 100.0,
                    max_step_height: 50.0,
                    min_time_interval: 0.1,
                    max_point_count: 1000
                });
                const username = ref(localStorage.getItem('username') || '管理员');
                const updateChartsInterval = ref(null);
                const activeConclusions = ref(['power', 'sway', 'cpu', 'memory', 'motor']);
                
                // 用户中心相关数据
                const adminId = ref(localStorage.getItem('adminId') || '100001');
                const lastLogin = ref('2023-05-10 14:30:25');
                const profileMenuActive = ref('basic');
                const logsLoading = ref(false);
                const logsTotal = ref(50);
                
                // 根据选择的菜单项返回标题
                const profileMenuTitle = computed(() => {
                    const titles = {
                        'basic': '基本资料',
                        'security': '安全设置',
                        'logs': '操作日志'
                    };
                    return titles[profileMenuActive.value] || '基本资料';
                });
                
                // 管理员个人资料
                const adminProfile = ref({
                    username: username.value,
                    email: 'admin@example.com',
                    realName: '管理员',
                    phone: '13800138000',
                    department: '研发部',
                    position: '系统管理员'
                });
                
                // 安全设置表单
                const securityForm = ref({
                    currentPassword: '',
                    newPassword: '',
                    confirmPassword: '',
                    mfaEnabled: false
                });
                
                // 操作日志数据
                const operationLogs = ref([
                    { time: '2023-05-15 10:30:25', operation: '登录系统', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-15 11:20:15', operation: '修改安全锁设置', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-14 15:45:30', operation: '删除用户', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-14 09:20:10', operation: '登录系统', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-13 16:30:22', operation: '修改密码', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-13 14:10:05', operation: '登录系统', ip: '192.168.1.105', status: '失败' },
                    { time: '2023-05-13 14:12:30', operation: '登录系统', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-12 11:25:40', operation: '更新系统配置', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-12 09:30:15', operation: '登录系统', ip: '192.168.1.100', status: '成功' },
                    { time: '2023-05-11 17:45:20', operation: '导出数据', ip: '192.168.1.100', status: '成功' }
                ]);
                
                // 保存个人资料
                const saveProfile = () => {
                    ElMessage.success('个人资料已更新');
                };
                
                // 重置个人资料表单
                const resetProfile = () => {
                    adminProfile.value = {
                        username: username.value,
                        email: 'admin@example.com',
                        realName: '管理员',
                        phone: '13800138000',
                        department: '研发部',
                        position: '系统管理员'
                    };
                };
                
                // 修改密码
                const changePassword = () => {
                    if (!securityForm.value.currentPassword) {
                        ElMessage.error('请输入当前密码');
                        return;
                    }
                    
                    if (!securityForm.value.newPassword) {
                        ElMessage.error('请输入新密码');
                        return;
                    }
                    
                    if (securityForm.value.newPassword !== securityForm.value.confirmPassword) {
                        ElMessage.error('两次输入的密码不一致');
                        return;
                    }
                    
                    ElMessage.success('密码修改成功，下次登录生效');
                    resetSecurityForm();
                };
                
                // 重置安全设置表单
                const resetSecurityForm = () => {
                    securityForm.value = {
                        currentPassword: '',
                        newPassword: '',
                        confirmPassword: '',
                        mfaEnabled: securityForm.value.mfaEnabled
                    };
                };
                
                // 设置双因素认证
                const setupMFA = () => {
                    ElMessageBox.alert(
                        '请使用身份验证器应用扫描下方二维码',
                        '设置双因素认证',
                        {
                            confirmButtonText: '确定',
                            callback: () => {
                                ElMessage.success('双因素认证已设置成功');
                            }
                        }
                    );
                };
                
                // 处理操作日志分页
                const handleLogsPageChange = (page) => {
                    logsLoading.value = true;
                    // 模拟加载数据
                    setTimeout(() => {
                        logsLoading.value = false;
                    }, 500);
                };
                
                // 处理用户相关操作（已弃用）
                const handleProfileAction = (command) => {
                    if (command === 'profile') {
                        activeTab.value = 'profile';
                    } else if (command === 'settings') {
                        activeTab.value = 'profile';
                        profileMenuActive.value = 'security';
                    } else if (command === 'logout') {
                        handleLogout();
                    }
                };

                // 耗电量分析结论
                const powerConsumptionConclusion = ref({
                    highType: 'gallop',
                    highValue: '30.5',
                    lowType: 'walk',
                    lowValue: '19.8',
                    peakTime: '12:00-14:00',
                    trend: '整体稳定，跑步模式下略有波动',
                    recommendation: '对于长时间运行任务，建议使用walk模式以节省电量。若需快速移动，trot模式比gallop模式更省电且速度相近。',
                    alert: '注意：电池电量低于30%时，建议避免使用gallop模式以防止意外关机。'
                });
                
                // 机身晃动分析结论
                const bodySwayConclusion = ref({
                    highType: 'jump',
                    highValue: '3.8',
                    lowType: 'walk',
                    lowValue: '1.2',
                    trend: '各步态稳定性良好，晃动幅度在安全范围内',
                    recommendation: '载重超过10kg时，建议使用walk或trot模式以保持稳定性。在不平坦地形上，减少gallop和jump的使用可以提高整体稳定性。',
                    alert: 'jump模式下的晃动幅度接近安全阈值，建议监控使用情况。'
                });
                
                // CPU负载分析结论
                const cpuLoadConclusion = ref({
                    maxLoad: '85',
                    maxLoadPoints: '2000',
                    maxLoadLength: '5000',
                    optimalPoints: '500-1000',
                    optimalLength: '2000-3000',
                    bottleneck: '点位数量是主要影响因素，轨迹长度影响较小',
                    recommendation: '为保持系统响应速度，建议将点位数控制在1000以内，特别是在处理复杂轨迹时。若必须使用高点位数，可考虑分批处理数据。',
                    alert: '点位数超过1500时CPU负载迅速增加，可能导致系统响应延迟。'
                });
                
                // 内存使用分析结论
                const memoryUsageConclusion = ref({
                    maxUsage: '78',
                    maxUsagePoints: '2000',
                    maxUsageLength: '5000',
                    trend: '随点位数和轨迹长度增加呈线性增长',
                    pointsImpact: '点位数每增加100，内存使用增加约2%',
                    recommendation: '对于资源受限设备，建议将点位数限制在1000以下，轨迹长度控制在3000mm以内，以保持内存使用在60%以下。长时间运行时应定期检查内存使用情况。',
                    alert: null
                });
                
                // 电机温度分析结论
                const motorTempConclusion = ref({
                    highestParam: '运行时间 60分钟，速度 50rad/s',
                    highestValue: '65',
                    safeRange: '25°C - 55°C',
                    riseRate: '每10分钟上升约5°C，30分钟后趋于平稳',
                    recommendation: '连续高速运行超过30分钟后建议休息5-10分钟，让电机温度回落。在环境温度较高时（>30°C），应适当减少连续运行时间。',
                    alert: '当前最高电机温度接近安全阈值(70°C)，建议关注并适当调整运行参数。'
                });
                
                // 初始化概览图表
                const initOverviewCharts = async () => {
                    try {
                        await nextTick();

                        const userTrendContainer = document.getElementById('userTrendChart');
                        const alertTrendContainer = document.getElementById('alertTrendChart');

                        if (!userTrendContainer || !alertTrendContainer) {
                            console.error('找不到图表容器元素');
                            return;
                        }

                        // 销毁现有的图表实例
                        if (charts.value.userActivity) {
                            charts.value.userActivity.dispose();
                        }
                        if (charts.value.alertTrend) {
                            charts.value.alertTrend.dispose();
                        }

                        // 初始化用户趋势图表
                        charts.value.userActivity = echarts.init(userTrendContainer);
                        charts.value.userActivity.setOption({
                            title: { text: '用户活跃趋势' },
                            tooltip: { trigger: 'axis' },
                            legend: { data: ['活跃用户', '新增用户'], bottom: 0 },
                            grid: { top: 50, right: 20, bottom: 40, left: 60 },
                            xAxis: { type: 'category', data: [] },
                            yAxis: { type: 'value' },
                            series: [
                                { name: '活跃用户', type: 'line', data: [] },
                                { name: '新增用户', type: 'bar', data: [] }
                            ]
                        });

                        // 初始化告警趋势图表
                        charts.value.alertTrend = echarts.init(alertTrendContainer);
                        charts.value.alertTrend.setOption({
                            title: { text: '告警趋势' },
                            tooltip: { trigger: 'axis' },
                            legend: { data: ['高级告警', '中级告警', '低级告警'], bottom: 0 },
                            grid: { top: 50, right: 20, bottom: 40, left: 60 },
                            xAxis: { type: 'category', data: [] },
                            yAxis: { type: 'value' },
                            series: [
                                { name: '高级告警', type: 'line', data: [] },
                                { name: '中级告警', type: 'line', data: [] },
                                { name: '低级告警', type: 'line', data: [] }
                            ]
                        });

                        // 添加窗口大小改变事件监听
                        window.addEventListener('resize', () => {
                            charts.value.userActivity?.resize();
                            charts.value.alertTrend?.resize();
                        });

                        // 获取并更新数据
                        await updateOverviewCharts();
                    } catch (error) {
                        console.error('初始化概览图表失败:', error);
                        ElMessage.error('初始化概览图表失败: ' + error.message);
                    }
                };

                // 更新概览图表
                const updateOverviewCharts = async () => {
                    try {
                        const response = await axios.get('/api/admin/analytics/overview');
                        const data = response.data;

                        if (!data) {
                            throw new Error('获取数据失败');
                        }

                        // 更新统计数据
                        stats.value = {
                            total_users: data.user_stats?.total_users || 0,
                            active_users: data.user_stats?.active_users || 0,
                            alerts: data.alert_stats?.total_alerts || 0
                        };

                        // 检查图表实例是否存在
                        if (!charts.value.userActivity || !charts.value.alertTrend) {
                            console.warn('图表实例未初始化');
                            return;
                        }

                        // 更新用户趋势图表
                        if (data.daily_trends && Array.isArray(data.daily_trends)) {
                            const dates = data.daily_trends.map(item => item.date);
                            const activeUsers = data.daily_trends.map(item => item.active_users || 0);
                            const newUsers = data.daily_trends.map(item => item.new_users || 0);

                            charts.value.userActivity.setOption({
                                xAxis: { data: dates },
                                series: [
                                    { name: '活跃用户', data: activeUsers },
                                    { name: '新增用户', data: newUsers }
                                ]
                            });
                        }

                        // 更新告警趋势图表
                        if (data.daily_trends && Array.isArray(data.daily_trends)) {
                            const dates = data.daily_trends.map(item => item.date);
                            const alerts = data.daily_trends.map(item => item.alerts || 0);
                            const highAlerts = alerts.map(a => (typeof a === 'number' ? Math.floor(a * 0.3) : 0));
                            const mediumAlerts = alerts.map(a => (typeof a === 'number' ? Math.floor(a * 0.4) : 0));
                            const lowAlerts = alerts.map(a => (typeof a === 'number' ? Math.floor(a * 0.3) : 0));

                            charts.value.alertTrend.setOption({
                                xAxis: { data: dates },
                                series: [
                                    { name: '高级告警', data: highAlerts },
                                    { name: '中级告警', data: mediumAlerts },
                                    { name: '低级告警', data: lowAlerts }
                                ]
                            });
                        }
                    } catch (error) {
                        console.error('更新概览图表失败:', error);
                        ElMessage.error('更新概览图表失败: ' + error.message);
                    }
                };

                // 初始化分析图表
                const initAnalyticsCharts = async () => {
                    try {
                        await nextTick();

                        // 获取所有图表容器
                        const containers = {
                            powerConsumption: document.getElementById('powerConsumptionChart'),
                            bodySway: document.getElementById('bodySwayChart'),
                            cpuLoad: document.getElementById('cpuLoadChart'),
                            memoryUsage: document.getElementById('memoryUsageChart'),
                            motorTemp: document.getElementById('motorTempChart')
                        };

                        // 检查容器是否存在
                        for (const [key, container] of Object.entries(containers)) {
                            if (!container) {
                                console.error(`找不到图表容器: ${key}`);
                                return;
                            }
                        }

                        // 销毁现有的图表实例
                        Object.entries(charts.value).forEach(([key, chart]) => {
                            if (chart && key !== 'userActivity' && key !== 'alertTrend') {
                                chart.dispose();
                            }
                        });

                        // 初始化耗电量分析图表
                        charts.value.powerConsumption = echarts.init(containers.powerConsumption);
                        charts.value.powerConsumption.setOption({
                            title: { text: '耗电量分析' },
                            tooltip: { trigger: 'axis' },
                            legend: { type: 'scroll', bottom: 0 },
                            grid: { top: 50, right: 20, bottom: 40, left: 60 },
                            xAxis: { type: 'category', data: [] },
                            yAxis: { type: 'value' },
                            series: []
                        });

                        // 初始化机身晃动分析图表
                        charts.value.bodySway = echarts.init(containers.bodySway);
                        charts.value.bodySway.setOption({
                            title: { text: '机身晃动分析' },
                            tooltip: { trigger: 'axis' },
                            legend: { type: 'scroll', bottom: 0 },
                            grid: { top: 50, right: 20, bottom: 40, left: 60 },
                            xAxis: { type: 'category', data: [] },
                            yAxis: { type: 'value' },
                            series: []
                        });

                        // 初始化CPU负载分析图表
                        charts.value.cpuLoad = echarts.init(containers.cpuLoad);
                        charts.value.cpuLoad.setOption({
                            title: { text: 'CPU负载分析' },
                            tooltip: { trigger: 'axis' },
                            grid: { top: 50, right: 20, bottom: 40, left: 60 },
                            xAxis: { type: 'category', data: [] },
                            yAxis: { type: 'value' },
                            series: []
                        });

                        // 初始化内存使用分析图表
                        charts.value.memoryUsage = echarts.init(containers.memoryUsage);
                        charts.value.memoryUsage.setOption({
                            title: { text: '内存使用分析' },
                            tooltip: { trigger: 'axis' },
                            grid: { top: 50, right: 20, bottom: 40, left: 60 },
                            xAxis: { type: 'category', data: [] },
                            yAxis: { type: 'value' },
                            series: []
                        });

                        // 初始化电机温度分析图表
                        charts.value.motorTemp = echarts.init(containers.motorTemp);
                        charts.value.motorTemp.setOption({
                            title: { text: '电机温度分析' },
                            tooltip: { trigger: 'axis' },
                            legend: { type: 'scroll', bottom: 0 },
                            grid: { top: 50, right: 20, bottom: 40, left: 60 },
                            xAxis: { type: 'category', data: [] },
                            yAxis: { type: 'value' },
                            series: []
                        });

                        // 添加窗口大小改变事件监听
                        window.addEventListener('resize', () => {
                            Object.values(charts.value).forEach(chart => chart?.resize());
                        });

                        // 获取并更新数据
                        await updateAnalyticsCharts();
                    } catch (error) {
                        console.error('初始化分析图表失败:', error);
                        ElMessage.error('初始化分析图表失败: ' + error.message);
                    }
                };

                // 更新分析图表
                const updateAnalyticsCharts = async () => {
                    try {
                        const [powerData, swayData, cpuData, memoryData, tempData] = await Promise.all([
                            axios.get('/api/admin/analytics/power-consumption'),
                            axios.get('/api/admin/analytics/body-sway'),
                            axios.get('/api/admin/analytics/cpu-load'),
                            axios.get('/api/admin/analytics/memory-usage'),
                            axios.get('/api/admin/analytics/motor-temperature')
                        ]);

                        // 更新耗电量分析图表
                        if (charts.value.powerConsumption && powerData.data) {
                            const { gait_types, timestamps, power_consumption } = powerData.data;
                            charts.value.powerConsumption.setOption({
                                legend: { data: gait_types },
                                xAxis: { data: timestamps },
                                series: gait_types.map((type, index) => ({
                                    name: type,
                                    type: 'line',
                                    data: power_consumption.map(pc => pc[index])
                                }))
                            });
                        }

                        // 更新机身晃动分析图表
                        if (charts.value.bodySway && swayData.data) {
                            const { gait_types, timestamps, sway_data } = swayData.data;
                            charts.value.bodySway.setOption({
                                legend: { data: gait_types },
                                xAxis: { data: timestamps },
                                series: gait_types.map((type, index) => ({
                                    name: type,
                                    type: 'line',
                                    data: sway_data.map(sd => sd[index])
                                }))
                            });
                        }

                        // 更新CPU负载分析图表
                        if (charts.value.cpuLoad && cpuData.data) {
                            const { point_counts, trajectory_lengths, cpu_loads } = cpuData.data;
                            
                            // 更改为热力图展示
                            charts.value.cpuLoad.setOption({
                                title: { 
                                    text: 'CPU负载分析',
                                    left: 'center'
                                },
                                tooltip: { 
                                    position: 'top',
                                    formatter: function (params) {
                                        return `点位数: ${point_counts[params.data[0]]}<br>` +
                                               `轨迹长度: ${trajectory_lengths[params.data[1]]}mm<br>` +
                                               `CPU负载: ${params.data[2]}%`;
                                    }
                                },
                                grid: {
                                    top: 50,
                                    right: 80,
                                    bottom: 60,
                                    left: 80
                                },
                                xAxis: {
                                    type: 'category',
                                    name: '轨迹长度(mm)',
                                    data: trajectory_lengths,
                                    splitArea: {
                                        show: true
                                    }
                                },
                                yAxis: {
                                    type: 'category',
                                    name: '点位数',
                                    data: point_counts,
                                    splitArea: {
                                        show: true
                                    }
                                },
                                visualMap: {
                                    min: 0,
                                    max: 100,
                                    calculable: true,
                                    orient: 'horizontal',
                                    left: 'center',
                                    bottom: 10,
                                    color: ['#d94e5d', '#eac736', '#50a3ba']
                                },
                                series: [{
                                    name: 'CPU负载',
                                    type: 'heatmap',
                                    data: cpu_loads.map((row, i) => 
                                        row.map((load, j) => [j, i, load])
                                    ).flat(),
                                    label: {
                                        show: false
                                    },
                                    emphasis: {
                                        itemStyle: {
                                            shadowBlur: 10,
                                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                        }
                                    }
                                }]
                            });
                        }

                        // 更新内存使用分析图表
                        if (charts.value.memoryUsage && memoryData.data) {
                            const { point_counts, trajectory_lengths, memory_usage } = memoryData.data;
                            
                            // 更改为热力图展示
                            charts.value.memoryUsage.setOption({
                                title: { 
                                    text: '内存使用分析',
                                    left: 'center'
                                },
                                tooltip: { 
                                    position: 'top',
                                    formatter: function (params) {
                                        return `点位数: ${point_counts[params.data[0]]}<br>` +
                                               `轨迹长度: ${trajectory_lengths[params.data[1]]}mm<br>` +
                                               `内存使用: ${params.data[2]}%`;
                                    }
                                },
                                grid: {
                                    top: 50,
                                    right: 80,
                                    bottom: 60,
                                    left: 80
                                },
                                xAxis: {
                                    type: 'category',
                                    name: '轨迹长度(mm)',
                                    data: trajectory_lengths,
                                    splitArea: {
                                        show: true
                                    }
                                },
                                yAxis: {
                                    type: 'category',
                                    name: '点位数',
                                    data: point_counts,
                                    splitArea: {
                                        show: true
                                    }
                                },
                                visualMap: {
                                    min: 0,
                                    max: 100,
                                    calculable: true,
                                    orient: 'horizontal',
                                    left: 'center',
                                    bottom: 10,
                                    color: ['#50a3ba', '#eac736', '#d94e5d']
                                },
                                series: [{
                                    name: '内存使用',
                                    type: 'heatmap',
                                    data: memory_usage.map((row, i) => 
                                        row.map((usage, j) => [j, i, usage])
                                    ).flat(),
                                    label: {
                                        show: false
                                    },
                                    emphasis: {
                                        itemStyle: {
                                            shadowBlur: 10,
                                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                        }
                                    }
                                }]
                            });
                        }

                        // 更新电机温度分析图表
                        if (charts.value.motorTemp && tempData.data) {
                            const { parameters, temperatures } = tempData.data;
                            charts.value.motorTemp.setOption({
                                legend: { data: Object.keys(temperatures) },
                                xAxis: { data: parameters },
                                series: Object.entries(temperatures).map(([param, values]) => ({
                                    name: param,
                                    type: 'line',
                                    data: values
                                }))
                            });
                        }
                    } catch (error) {
                        console.error('更新分析图表失败:', error);
                        ElMessage.error('更新分析图表失败: ' + error.message);
                    }
                };

                // 更新分析结论
                const updateAnalyticsConclusions = async () => {
                    try {
                        // 这里可以添加从后端获取最新分析结论的逻辑
                        // 目前使用静态数据作为示例
                        
                        // 模拟从后端获取数据的延迟
                        await new Promise(resolve => setTimeout(resolve, 500));
                        
                        // 更新电量分析结论（模拟数据）
                        powerConsumptionConclusion.value = {
                            highType: 'gallop',
                            highValue: (Math.random() * 5 + 28).toFixed(1),
                            lowType: 'walk',
                            lowValue: (Math.random() * 3 + 18).toFixed(1),
                            peakTime: '12:00-14:00',
                            trend: Math.random() > 0.5 ? '整体稳定，跑步模式下略有波动' : '近期整体耗电量有所增加，特别是在jump模式下',
                            recommendation: '对于长时间运行任务，建议使用walk模式以节省电量。若需快速移动，trot模式比gallop模式更省电且速度相近。',
                            alert: Math.random() > 0.7 ? '注意：电池电量低于30%时，建议避免使用gallop模式以防止意外关机。' : null
                        };
                        
                        // 更新其他结论...类似逻辑
                    } catch (error) {
                        console.error('更新分析结论失败:', error);
                    }
                };

                // 组件挂载时的操作
                onMounted(async () => {
                    // 验证用户身份
                    const token = localStorage.getItem('token');
                    const isAdmin = localStorage.getItem('isAdmin') === 'true';
                    
                    if (!token || !isAdmin) {
                        ElMessage.error('请先登录');
                        window.location.href = 'login.html';
                        return;
                    }

                    // 初始化加载，设置loading状态
                    loading.value = true;
                    
                    try {
                        // 初始化概览图表
                        if (activeTab.value === 'overview') {
                            await initOverviewCharts();
                        }
                        
                        // 加载用户数据和告警数据
                        await fetchUsers();
                        await fetchAlerts();
                        await fetchSafetyLocks();
                    } catch (error) {
                        console.error('初始化数据失败:', error);
                        ElMessage.error('初始化数据失败');
                    } finally {
                        // 确保无论成功失败都结束loading状态
                        loading.value = false;
                    }
                });

                // 监听标签页变化
                watch(activeTab, async (newTab, oldTab) => {
                    // 防止重复加载
                    if (loading.value) return;
                    
                    // 清除之前的定时器
                    if (updateChartsInterval.value) {
                        clearInterval(updateChartsInterval.value);
                        updateChartsInterval.value = null;
                    }

                    loading.value = true;
                    
                    try {
                        if (newTab === 'overview') {
                            await initOverviewCharts();
                            updateChartsInterval.value = setInterval(updateOverviewCharts, 30000);
                        } else if (newTab === 'analysis') {
                            await initAnalyticsCharts();
                            updateChartsInterval.value = setInterval(updateAnalyticsCharts, 30000);
                        } else if (newTab === 'users') {
                            // 加载用户数据
                            await fetchUsers();
                        } else if (newTab === 'alerts') {
                            // 加载告警数据
                            await fetchAlerts();
                        } else if (newTab === 'settings') {
                            // 加载安全锁设置
                            await fetchSafetyLocks();
                        }
                    } catch (error) {
                        handleApiError(error, `切换到${newTab}标签页失败`);
                    } finally {
                        loading.value = false;
                    }
                });

                // 组件卸载时清理
                onUnmounted(() => {
                    // 清除定时器
                    if (updateChartsInterval.value) {
                        clearInterval(updateChartsInterval.value);
                        updateChartsInterval.value = null;
                    }

                    // 销毁图表实例
                    Object.values(charts.value).forEach(chart => {
                        if (chart) {
                            chart.dispose();
                        }
                    });

                    // 移除窗口大小改变事件监听
                    window.removeEventListener('resize', () => {
                        charts.value.userActivity?.resize();
                        charts.value.alertTrend?.resize();
                    });
                });

                // 发送控制指令
                const sendControl = async () => {
                    try {
                        await axios.post('/api/admin/motion/control', controlForm.value);
                        ElMessage.success('控制指令已发送');
                    } catch (error) {
                        console.error('发送控制指令失败:', error);
                        ElMessage.error('发送控制指令失败');
                    }
                };

                // 紧急停止
                const emergencyStop = async () => {
                    try {
                        await axios.post('/api/admin/motion/control', {
                            gait_type: 'stop',
                            speed: 0,
                            direction: 'stop'
                        });
                        ElMessage.success('紧急停止指令已发送');
                    } catch (error) {
                        console.error('发送紧急停止指令失败:', error);
                        ElMessage.error('发送紧急停止指令失败');
                    }
                };

                // 获取用户列表
                const fetchUsers = async () => {
                    try {
                        const response = await axios.get('/api/admin/users');
                        users.value = response.data;
                    } catch (error) {
                        console.error('获取用户列表失败:', error);
                        ElMessage.error('获取用户列表失败');
                    }
                };

                // 处理用户操作
                const handleUserAction = async (action, user) => {
                    try {
                        if (action === 'delete') {
                            await axios.delete(`/api/admin/user/${user.id}`);
                            ElMessage.success('用户已删除');
                            await fetchUsers();
                        }
                    } catch (error) {
                        console.error('用户操作失败:', error);
                        ElMessage.error('操作失败');
                    }
                };

                // 获取告警列表
                const fetchAlerts = async () => {
                    try {
                        const response = await axios.get('/api/alerts');
                        alerts.value = response.data.alerts;
                    } catch (error) {
                        console.error('获取告警列表失败:', error);
                        ElMessage.error('获取告警列表失败');
                    }
                };

                // 处理告警操作
                const handleAlertAction = async (action, alert) => {
                    try {
                        const newStatus = action === 'resolve' ? 'processed' : 'unprocessed';
                        await axios.put(`/api/alerts/${alert.id}`, { status: newStatus });
                        alert.status = newStatus;
                        ElMessage.success('更新告警状态成功');
                    } catch (error) {
                        console.error('更新告警状态失败:', error);
                        ElMessage.error('更新告警状态失败');
                    }
                };

                // 获取安全锁设置
                const fetchSafetyLocks = async () => {
                    try {
                        const response = await axios.get('/api/admin/safety-locks');
                        safetyLocks.value = response.data;
                    } catch (error) {
                        console.error('获取安全锁设置失败:', error);
                        ElMessage.error('获取安全锁设置失败');
                    }
                };

                // 更新安全锁设置
                const updateSafetyLocks = async () => {
                    try {
                        loading.value = true;
                        await axios.post('/api/admin/safety-locks', safetyLocks.value);
                        ElMessage.success('安全锁设置已更新');
                    } catch (error) {
                        console.error('更新安全锁设置失败:', error);
                        ElMessage.error(error.response?.data?.message || '更新安全锁设置失败');
                    } finally {
                        loading.value = false;
                    }
                };

                // 重置安全锁设置
                const resetSafetyLocks = () => {
                    safetyLocks.value = {
                    max_motor_temp: 45.0,
                    max_cpu_usage: 80.0,
                    max_memory_usage: 90.0,
                    max_sway_angle: 30.0,
                    min_battery_level: 20.0,
                    max_stride_length: 100.0,
                    max_step_height: 50.0,
                    min_time_interval: 0.1,
                    max_point_count: 1000
                    };
                };

                // 获取告警级别样式
                const getAlertLevelType = (level) => {
                    const types = {
                        'low': 'info',
                        'medium': 'warning',
                        'high': 'danger'
                    };
                    return types[level] || 'info';
                };

                // 格式化日期
                const formatDate = (date) => {
                    return new Date(date).toLocaleString();
                };

                // 退出登录
                const handleLogout = () => {
                    localStorage.removeItem('token');
                    localStorage.removeItem('isAdmin');
                    localStorage.removeItem('username');
                    window.location.href = 'login.html';
                };

                // 添加一个公共的异常处理函数来确保loading状态被重置
                const handleApiError = (error, message = '操作失败') => {
                    console.error(message + ':', error);
                    ElMessage.error(error.response?.data?.message || message);
                    loading.value = false;  // 确保出错时也会关闭loading
                };

                // 刷新分析数据
                const handleAnalyticsRefresh = async () => {
                    if (loading.value) return; // 防止重复点击
                    
                    loading.value = true;
                    try {
                        await Promise.all([
                            updateAnalyticsCharts(),
                            updateAnalyticsConclusions()
                        ]);
                        ElMessage.success('数据已更新');
                    } catch (error) {
                        handleApiError(error, '刷新数据失败');
                        return;
                    } finally {
                        loading.value = false;
                    }
                };

                return {
                    loading,
                    activeTab,
                    stats,
                    users,
                    alerts,
                    controlForm,
                    safetyLocks,
                    sendControl,
                    emergencyStop,
                    handleUserAction,
                    handleAlertAction,
                    updateSafetyLocks,
                    resetSafetyLocks,
                    handleLogout,
                    formatDate,
                    getAlertLevelType,
                    handleAnalyticsRefresh,
                    username,
                    activeConclusions,
                    powerConsumptionConclusion,
                    bodySwayConclusion,
                    cpuLoadConclusion,
                    memoryUsageConclusion,
                    motorTempConclusion
                };
            }
        });

        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html> 